<?php

namespace util;

class Curl
{
    /**
     * Curl请求
     * @param string $url   链接
     * @param array $data   传入数据,只支持一维数组
     * @param array $arr    其它参数
     * @return bool|string
     */
    public static function curl_request($url = '', $data = [], $arr = [])
    {
        if (empty($url)) {
            return false;
        }

        //处理 header
        $header = [];
        if (!isset($arr['header'])) {
            $header[] = "content-type:application/x-www-form-urlencoded;charset=utf-8";
        } else {
            $header = $arr['header'];
        }
        if (isset($arr['appid'])) {
            $header[] = "Kg-Appid:" . $arr['appid'];
        }
        if (isset($arr['token'])) {
            $header[] = "Kg-Token:" . $arr['token'];
        }
        if (!isset($arr['method'])) {
            $method = 'GET';
        } else {
            $method = $arr['method'];
        }
        if (!isset($arr['timeout'])) {
            $timeout = 5;
        } else {
            $timeout = $arr['timeout'];
        }

        // curl完成初始化
        $curl = curl_init();
        if (defined('CURLOPT_IPRESOLVE') && defined('CURL_IPRESOLVE_V4')) {
            curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); //强制使用IPV4协议解析域名
        }

        if (isset($arr['appid'])) {
            // 实时数据
            $app = (new \app\common\service\sys\ClientService())->getInfoByWhere(['app_id' => $arr['appid']]);
            // 是否存在
            if (empty($app)) {
                return false;
            }
        }
        //保证有参数
        if (!is_string($data) && empty($data)) {
            $data = [
                'formdomain' => config('kaige.domain_name')
            ];
        }

        if (!empty($data)) {
            foreach ($data as $key => $val) {
                $data[$key] =  urlencode($val);
            }
            //数组排序
            ksort($data);
            foreach ($data as $k9 => &$v9) { //一层数组排一下序
                if (is_array($v9)) {
                    ksort($v9);
                }
            }
            $upstr = count($data) > 0 ? http_build_query($data) : '';
            $signlocal = md5(sha1($upstr) . $app['app_salt']);
            $data['signature'] = $signlocal;
            $upstr = $upstr . '&signature=' . $signlocal;
        } else {
            $upstr = '';
        }

        if (is_string($data)) {
            $strPOST = $data;
        } else {
            $aPOST = array();
            foreach ($data as $key => $val) {
                $aPOST[] = $key . "=" . urlencode($val);
            }
            $strPOST = join("&", $aPOST);
        }
        //默认是GET请求,仅2种 GET,POST
        // trace($strPOST);
        switch (strtoupper($method)) {
            case 'GET':
                $url = $url . '?' . $upstr; //只能用 url传参，所以提前 签名好再拼成字串
                break;
            case 'POST':
                curl_setopt($curl, CURLOPT_POST, 1); //请求方式为post请求
                curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); //请求数据
                break;
            default:
                return false; //中断返回
        }
        curl_setopt($curl, CURLOPT_URL, $url); //需要获取的URL地址
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //只获取页面内容，但不输出
        if (stripos($url, "https://") !== false) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //https请求 不验证证书
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); //https请求 不验证HOST
            curl_setopt($curl, CURLOPT_SSLVERSION, 1); //设置SSL协议版本号
        }
        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout); //超时
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header); //模拟的header头
        curl_setopt($curl, CURLINFO_HEADER_OUT, 1); //启用时追踪句柄的请求字符串

        try {
            $result = curl_exec($curl); //执行请求--结果一般是字符串
            $headertxt = curl_getinfo($curl, CURLINFO_HEADER_OUT);
            $result_info  = curl_getinfo($curl); //获取连接资源句柄的信息
            curl_close($curl); //关闭curl，释放资源
            if (intval($result_info["http_code"]) == 200) {
                if ($arr['result'] == 'json') { //如果知道 返回结果是json 则转换
                    $result = json_decode($result, true);
                }
                return $result;
            } else {
                return false;
            }
        } catch (\Exception $e) {
            return false;
        }
    }
}
